package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("SupplierRestController")
public class SupplierRestController extends CmiEmaController {

	/**
	 * Create a new Supplier entity
	 * 
	 */
	@RequestMapping(value = "/newSupplier", method = RequestMethod.POST)
	@ResponseBody
	public Object newSupplier(@RequestBody Supplier supplier) {
		supplierService.saveSupplier(supplier);
		return JSONObject.parse(cmiPsonService.toJsonString(supplierDAO.findSupplierByPrimaryKey(supplier.getId()), 2));
	}

	@RequestMapping(value = "/restNewSupplier", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewSupplier(@RequestBody String supplierJson) {
		Supplier supplier = new Gson().fromJson(supplierJson, Supplier.class);
		appendReferences(supplier);
		supplierService.saveSupplier(supplier);
		return JSONObject.parse(cmiPsonService.toJsonString(supplierDAO.findSupplierByPrimaryKey(supplier.getId()), 2));
	}

	@RequestMapping(value = "/saveSupplier", method = RequestMethod.PUT)
	@ResponseBody
	public Supplier saveSupplier(@RequestBody Supplier supplier) {
		supplierService.saveSupplier(supplier);
		return supplierDAO.findSupplierByPrimaryKey(supplier.getId());
	}

	@RequestMapping(value = "/restSaveSupplier", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveSupplier(@RequestBody String supplierJson) {
		Supplier supplier = new Gson().fromJson(supplierJson, Supplier.class);
		appendReferences(supplier);
		CmiPsonService cmiPsonService = new CmiPsonService();
		supplierService.saveSupplier(supplier);
		return JSONObject.parse(cmiPsonService.toJsonString(supplierDAO.findSupplierByPrimaryKey(supplier.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteSupplier/{supplierId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteSupplier(@PathVariable Integer supplierId) {
		Supplier supplier = supplierDAO.findSupplierByPrimaryKey(supplierId);
		supplierService.deleteSupplier(supplier);
	}

	@RequestMapping(value = "/restConfirmDeleteSuppliers")
	@ResponseBody
	public Object restConfirmDeleteSuppliers(@RequestBody Set<Integer> deleteSuppliersIds) {
		Set<Supplier> deleteSuppliers = supplierDAO.findSuppliersByIds(deleteSuppliersIds);
		Set<Supplier> referencedSuppliers = supplierService.loadReferenceSuppliers(deleteSuppliers);
		deleteSuppliers.removeAll(referencedSuppliers);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedSuppliers);
		jsonObject.put("deleteEntitys", deleteSuppliers);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteSuppliers")
	@ResponseBody
	public Object restDeleteSuppliers(@RequestBody Set<Supplier> deleteSuppliers) {
		Iterator<Supplier> iterator = deleteSuppliers.iterator();
		while (iterator.hasNext()) {
			Supplier currentSupplier = iterator.next();
			supplierService.deleteSupplier(currentSupplier);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listSuppliers");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadSupplier/{supplierId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSupplier(@PathVariable Integer supplierId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(supplierDAO.findSupplierByPrimaryKey(supplierId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadSupplierAddress/{supplierId}/address", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSupplierAddress(@PathVariable Integer supplierId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(supplierDAO.findSupplierByPrimaryKey(supplierId).getAddress(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadSupplierPurchaseadditives/{supplierId}/purchaseadditives/{relatedpurchaseadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSupplierPurchaseadditives(@PathVariable Integer supplierId,
			@PathVariable Integer relatedpurchaseadditiveId, @RequestBody CmiPagination cmiPagination) {
		Purchaseadditive purchaseadditive = purchaseadditiveDAO
				.findPurchaseadditiveByPrimaryKey(relatedpurchaseadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchaseadditive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadSupplierPurchasematerials/{supplierId}/purchasematerials/{relatedpurchasematerialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadSupplierPurchasematerials(@PathVariable Integer supplierId,
			@PathVariable Integer relatedpurchasematerialId, @RequestBody CmiPagination cmiPagination) {
		Purchasematerial purchasematerial = purchasematerialDAO
				.findPurchasematerialByPrimaryKey(relatedpurchasematerialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchasematerial, 2, cmiPagination));
	}

	public void appendReferences(Supplier supplier) {

		Address address = supplier.getAddress();
		if (address != null)
			supplier.setAddress(addressService.findAddressByPrimaryKey(address.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchaseadditive> purchaseadditivesForSupplier = new HashSet<>();
		for (Purchaseadditive purchaseadditive_Supplier : supplier.getPurchaseadditivesForSupplier()) {
			purchaseadditivesForSupplier
					.add(purchaseadditiveService.findPurchaseadditiveByPrimaryKey(purchaseadditive_Supplier.getId()));
		}
		supplier.setPurchaseadditivesForSupplier(purchaseadditivesForSupplier);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchasematerial> purchasematerialsForSupplier = new HashSet<>();
		for (Purchasematerial purchasematerial_Supplier : supplier.getPurchasematerialsForSupplier()) {
			purchasematerialsForSupplier
					.add(purchasematerialService.findPurchasematerialByPrimaryKey(purchasematerial_Supplier.getId()));
		}
		supplier.setPurchasematerialsForSupplier(purchasematerialsForSupplier);
	}

	@RequestMapping(value = "/restGetSupplierAddress/{supplierId}/address", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetSupplierAddress(@PathVariable Integer supplierId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(supplierDAO.findSupplierByPrimaryKey(supplierId).getAddress(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetSupplierPurchaseadditives/{supplierId}/purchaseadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetSupplierPurchaseadditives(@PathVariable Integer supplierId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				supplierDAO.findSupplierByPrimaryKey(supplierId).getPurchaseadditivesForSupplier(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetSupplierPurchasematerials/{supplierId}/purchasematerials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetSupplierPurchasematerials(@PathVariable Integer supplierId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				supplierDAO.findSupplierByPrimaryKey(supplierId).getPurchasematerialsForSupplier(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListSuppliers", method = RequestMethod.GET)
	@ResponseBody
	public Object restListSuppliers() {
		return JSONObject.parse(cmiPsonService.toJsonString(supplierService.loadSuppliers(), 2));
	}

	@RequestMapping(value = "/restListSuppliersPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListSuppliersPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = supplierPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Supplier> suppliers = supplierDAO.findAllSuppliers(startResult, cmiPagination.getPaginationSize());
		String supplierString = cmiPsonService.toPsonString(suppliers, 2, cmiPagination);

		return JSONObject.parse(supplierString);
	}

	@RequestMapping("/supplierSelectBox")
	@ResponseBody
	public JSONObject supplierSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Address":
				entitySet = addressService.loadAddresssByIdSet(searchValue);
				break;

			// 被引用键
			case "Purchaseadditive":
				entitySet = purchaseadditiveService.loadPurchaseadditivesByIdSet(searchValue);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialService.loadPurchasematerialsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAllAddresss((pageNumber - 1) * paginationSize, paginationSize);
				count = addressService.countAddresss();
				break;

			// 被引用键
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findAllPurchaseadditives((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchaseadditiveService.countPurchaseadditives();
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findAllPurchasematerials((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchasematerialService.countPurchasematerials();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAddressByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = addressService.countAddresssByName(queryword);
				break;

			// 被引用键
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findPurchaseadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchaseadditiveService.countPurchaseadditivesByName(queryword);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findPurchasematerialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchasematerialService.countPurchasematerialsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
